package com.heima.wemedia.gateway.filter;

import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthGloblFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.判断是否是登录请求,是就放行
        if( request.getURI().getPath().contains("/login")){
            //容易忘记return
            return chain.filter(exchange);
        }

        //2.获取token,校验token是否存在
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            //返回错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3.校验token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token); //获取payload载荷 包含过期时间
            int verifyToken = AppJwtUtil.verifyToken(claimsBody);  //校验token是否过期 1和2是有问题的情况
            if(verifyToken == 1 || verifyToken == 2){
                //返回错误
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //解析id
            Long id = claimsBody.get("id", Long.class);
            //将id存放到请求头中进行传递
            ServerHttpRequest newRequest = request.mutate()
                    .header("userId", id.toString()).build();
            exchange.mutate().request(newRequest).build();

        } catch (Exception e) {
            //返回错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
